/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.comac.ins.common.core.domain.R;
import com.comac.ins.common.core.domain.model.LoginUser;
import com.comac.ins.common.log.annotation.Log;
import com.comac.ins.common.log.enums.BusinessType;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.common.satoken.utils.LoginHelper;
import com.comac.ins.isfd.domain.bo.FastenerOriginalInfoBo;
import com.comac.ins.isfd.domain.bo.query.FastenerOriginalInfoQueryBo;
import com.comac.ins.isfd.domain.bo.query.FastenerQueryBo;
import com.comac.ins.isfd.domain.bo.query.FasteneraAllowableValueQueryBo;
import com.comac.ins.isfd.domain.bo.query.FastenerInfoAllowableValueQueryBo;
import com.comac.ins.isfd.domain.bo.query.FastenerModelAllowableValueQueryBo;
import com.comac.ins.isfd.domain.bo.query.ResultSplitAndSaveExcelTablesBo;
import com.comac.ins.isfd.domain.vo.FastenerCountObjectVo;
import com.comac.ins.isfd.domain.vo.FastenerImportObjectVo;
import com.comac.ins.isfd.domain.vo.FastenerInfoVo;
import com.comac.ins.isfd.domain.vo.FastenerModelTreeVo;
import com.comac.ins.isfd.domain.vo.IsfdFastenerCountObjectVo;
import com.comac.ins.isfd.domain.vo.IsfdTreeNodeVo;
import com.comac.ins.isfd.service.IFastenerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 紧固件controller
 *
 * @author hxloongs
 * @date 2024-7-3
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/fastener")
public class FastenerController {

    @Autowired
    private IFastenerService iFastenerService;

    @SaCheckPermission("isfd:fastener:count")
    @GetMapping("/list/count")
    @Operation(summary = "统计紧固件各类型的数量接口", security = @SecurityRequirement(name = "isfd:fastener:count"))
    public R<List<FastenerCountObjectVo>> listCount() {
        return R.ok(iFastenerService.listCount());
    }

    @SaCheckPermission("isfd:fastener:count")
    @GetMapping("/list/count/{field}")
    @Operation(summary = "统计紧固件各类型的数量接口", security = @SecurityRequirement(name = "isfd:fastener:count"))
    public R<List<IsfdFastenerCountObjectVo>> listCountByListByField(@PathVariable String field) {
        return R.ok(iFastenerService.listCountByListByField(field));
    }

    /**
     * 查询紧固件库数据的树形接口
     */
    @SaCheckPermission("isfd:fastener:tree")
    @GetMapping("/list/tree")
    @Operation(summary = "查询紧固件库数据的树形接口", security = @SecurityRequirement(name = "isfd:fastener:tree"))
    public R<IsfdTreeNodeVo> listTree() {
        return R.ok(iFastenerService.listTree());
    }

    @SaCheckPermission("isfd:fastener:list")
    @PostMapping("/list")
    @Operation(summary = "紧固件分页查询列表接口", security = @SecurityRequirement(name = "isfd:fastener:list"))
    public TableDataInfo<FastenerImportObjectVo> getFastenerList(@RequestBody FastenerQueryBo queryBo) {
        return iFastenerService.queryPageList(queryBo);
    }

    /**
     * 查询紧固件库数据许用值的接口
     */
    @SaCheckPermission("isfd:fastener:allowable")
    @PostMapping("/allowable/list")
    @Operation(summary = "查询紧固件库数据许用值的接口", security = @SecurityRequirement(name = "isfd:fastener:allowable"))
    public R<List<String>> allowableValueList(@RequestBody FasteneraAllowableValueQueryBo queryBo) {
        return R.ok(iFastenerService.allowableValueList(queryBo));
    }

    /**
     * 导入紧固件库数据许用值的接口
     */
    @SaCheckPermission("isfd:fastener:allowable")
    @PostMapping("/allowable/upload/excel")
    @Operation(summary = "导入紧固件库数据许用值的接口", security = @SecurityRequirement(name = "isfd:fastener:allowable"))
    public R<List<ResultSplitAndSaveExcelTablesBo>> allowableValueUploadExcel(@RequestPart(value = "file", required = false) MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return R.fail("上传文件不能为空");
        }

        List<ResultSplitAndSaveExcelTablesBo> resultSplitAndSaveExcelTablesBoList = iFastenerService.allowableValueUploadExcel(file);
        return R.ok(resultSplitAndSaveExcelTablesBoList);

    }

    /**
     * 查询紧固件库数据的接口
     */
    @SaCheckPermission("isfd:fastener:allowable")
    @PostMapping("/model/allowable/tree")
    @Operation(summary = "查询紧固件库数据的接口", security = @SecurityRequirement(name = "isfd:fastener:allowable"))
    public R<List<IsfdTreeNodeVo<IsfdTreeNodeVo<FastenerModelTreeVo>>>> getFasteneraModelTreeList(@RequestBody FastenerModelAllowableValueQueryBo queryBo) {
        return R.ok(iFastenerService.getFastenerModelTreeList(queryBo));
    }

    /**
     * 查询紧固件库数据的接口
     */
    @SaCheckPermission("isfd:fastener:allowable")
    @PostMapping("/info/allowable/list")
    @Operation(summary = "查询紧固件库数据的接口", security = @SecurityRequirement(name = "isfd:fastener:allowable"))
    public R<List<FastenerInfoVo>> getFastenerModelAllowableValueList(@RequestBody FastenerInfoAllowableValueQueryBo queryBo) {
        return R.ok(iFastenerService.getFastenerModelAllowableValueList(queryBo));
    }

    /**
     * 查询紧固件库原始信息的接口
     */
    @SaCheckPermission("isfd:fastener:original")
    @PostMapping("/info/original/list")
    @Operation(summary = "查询紧固件库原始数据的接口", security = @SecurityRequirement(name = "isfd:fastener:original"))
    public R<List<FastenerOriginalInfoBo>> getFastenerOriginalInfoList(
        @RequestBody FastenerOriginalInfoQueryBo queryBo) {
        return R.ok(iFastenerService.getFastenerOriginalInfoList(queryBo));
    }

    /**
     * 导入紧固件库原始信息的接口
     */
    @SaCheckPermission("isfd:fastener:original")
    @PostMapping("/info/original/excel")
    @Operation(summary = "导入紧固件库原始信息的接口", security = @SecurityRequirement(name = "isfd:fastener:original"))
    public R<Long> originalInfoUploadExcel(@RequestParam("file") MultipartFile file) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        File tempFile = null;
        try {
            // 校验文件
            if (file == null || file.isEmpty()) {
                return R.fail("上传文件不能为空");
            }

            // 创建临时文件
            tempFile = File.createTempFile("fastenerOriginalImport_", ".xlsx");
            file.transferTo(tempFile);

            // 调用导入服务
            Long successCount = iFastenerService.originalInfoUploadExcel(tempFile, loginUser);
            return R.ok(successCount);
        } catch (Exception e) {
            return R.fail("导入失败：" + e.getMessage());
        } finally {
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

    /**
     * 导出【紧固件库】模板
     */
    @SaCheckPermission("isfd:fastener:export")
    @Log(title = "【紧固件库】原始模板", businessType = BusinessType.EXPORT)
    @GetMapping("/info/original/template")
    public void downloadTemplate(HttpServletResponse response) {
        iFastenerService.exportTemplate(response);
    }

    /**
     * 导出【紧固件库】原始信息
     */
    @SaCheckPermission("isfd:fastener:export")
    @Log(title = "【紧固件库】原始信息", businessType = BusinessType.EXPORT)
    @PostMapping("/info/original/export")
    public void exportOriginalInfo(@RequestBody FastenerOriginalInfoQueryBo queryBo, HttpServletResponse response) {
        iFastenerService.exportOriginalInfo(queryBo, response);
    }

    /**
     * 批量上传许用值的所有Excel文件
     *
     * @param files 多个Excel文件
     * @return 上传结果
     */
    @SaCheckPermission("isfd:fastener:allowable")
    @PostMapping("/allowable/batch-upload")
    public R<List<List<ResultSplitAndSaveExcelTablesBo>>> batchUploadExcelFiles(
        @RequestPart(value = "files", required = false) MultipartFile[] files) {

        // 校验文件数组是否为空
        if (files == null || files.length == 0) {
            return R.fail("请选择至少一个Excel文件上传");
        }

        List<List<ResultSplitAndSaveExcelTablesBo>> allResults = new ArrayList<>();

        try {
            // 循环处理每个文件，调用单个文件导入接口的业务逻辑
            for (MultipartFile file : files) {
                // 跳过空文件
                if (file.isEmpty()) {
                    ResultSplitAndSaveExcelTablesBo resultSplitAndSaveExcelTablesBo = new ResultSplitAndSaveExcelTablesBo();
                    resultSplitAndSaveExcelTablesBo.setMessage("跳过空文件：" + file.getOriginalFilename());
                    List<ResultSplitAndSaveExcelTablesBo> resultSplitAndSaveExcelTablesBoList = new LinkedList<>();
                    allResults.add(resultSplitAndSaveExcelTablesBoList);
                    continue;
                }

                // 调用单个文件导入的服务方法
                List<ResultSplitAndSaveExcelTablesBo> singleResult = iFastenerService.allowableValueUploadExcel(file);
                allResults.add(singleResult);
            }

            return R.ok(allResults);

        } catch (Exception e) {
            return R.fail("批量导入失败：" + e.getMessage());
        }
    }
}
